package com.centaline.androidsalesblog.application;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Bundle;
import android.support.multidex.MultiDex;

import com.android.volley.VolleyLog;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mobstat.StatService;
import com.centaline.androidsalesblog.BuildConfig;
import com.centaline.androidsalesblog.activities.MainActivity;
import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.constants.SprfConstant;
import com.centaline.androidsalesblog.events.RongConnectionStatus;
import com.centaline.androidsalesblog.events.RongReceiveMessage;
import com.centaline.androidsalesblog.model.databaseobject.BizUnitDo;
import com.centaline.androidsalesblog.model.databaseobject.UserDo;
import com.centaline.androidsalesblog.notification.RongNotification;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centanet.framework.glide.GlideLoad;
import com.centanet.framework.network.VolleyRequestQueue;
import com.centanet.framework.utils.AppUpdateUtil;
import com.centanet.framework.utils.SprfUtil;
import com.centanet.framework.utils.SysUtil;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechUtility;
import com.orhanobut.logger.LogLevel;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.litepal.LitePalApplication;
import org.litepal.tablemanager.Connector;

import java.util.Calendar;
import java.util.GregorianCalendar;

import cn.jpush.android.api.JPushInterface;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Message;
import io.rong.notification.PushNotificationMessage;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Application
 * Created by guilin on 15/12/15.
 */
public class SaleHouseApp extends LitePalApplication {

    private static final boolean DEBUG = BuildConfig.DEBUG;
    private int activityCount = 0;//开启的页面数量

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(base);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        /*全局日志*/
        Logger.init("Logger")
                .setMethodCount(0)
                .hideThreadInfo()
                .setLogLevel(DEBUG ? LogLevel.FULL : LogLevel.NONE);
        VolleyLog.DEBUG = DEBUG;
//        if (DEBUG) {//严格模式
//            StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
//                    .detectAll()
//                    .penaltyDeath()
//                    .build());
//            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
//                    .detectAll()
//                    .penaltyLog()
//                    .penaltyDeathOnNetwork()
//                    .build());
//        }
        String curProcessName = getCurProcessName();
        Logger.d("CurProcessName : %s", curProcessName);
        appInit(curProcessName);
        otherInit(curProcessName);
    }

    /**
     * app初始化
     */
    private void appInit(String curProcessName) {
        if (BuildConfig.APPLICATION_ID.equals(curProcessName)) {
            /*volley请求队列初始化*/
            AppUpdateUtil.setApkName(this, "zyzf");
            VolleyRequestQueue.init(this);
            /*创建数据库表*/
            Connector.getDatabase();
            AppConstant.init(this);
            AppConstant.IP = SysUtil.getLocalIpAddress();
            GlideLoad.loadWithWifi = !SprfUtil.getBoolean(this, SprfConstant.WIFI_SWITCH, true);
            registerActivityLifecycleCallbacks(activityLifecycleCallbacks);
            if (AppConstant.IsLogin) {
                RxDataBase.getUser()
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Action1<UserDo>() {
                            @Override
                            public void call(UserDo userDo) {
                                AppConstant.userDo = userDo;
                            }
                        });
                RxDataBase.getBizUnit()
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Action1<BizUnitDo>() {
                            @Override
                            public void call(BizUnitDo bizUnitDo) {
                                AppConstant.ShowTalk = bizUnitDo.isShowTalk();
                            }
                        });
            }
        }
    }

    /**
     * 第三方初始化
     */
    private void otherInit(String curProcessName) {
        if (BuildConfig.APPLICATION_ID.equals(curProcessName)) {
            /*百度SDK初始化*/
            SDKInitializer.initialize(this);
            /*百度定位初始化*/
            MyLocation.init(this);
            /*语音初始化*/
            SpeechUtility.createUtility(this, SpeechConstant.APPID + "=56c690b9");//56c690b9|57346e9e
            /*极光推送初始化*/
            JPushInterface.init(this);
            JPushInterface.setDebugMode(DEBUG);
            StatService.setDebugOn(DEBUG);
        }
        /*融云IM*/
        if (BuildConfig.APPLICATION_ID.equals(curProcessName) ||
                "io.rong.push".equals(curProcessName)) {
            RongIMClient.init(this);
            RongIMClient.setOnReceiveMessageListener(onReceiveMessageListener);
            RongIMClient.setOnReceivePushMessageListener(new RongIMClient.OnReceivePushMessageListener() {
                @Override
                public boolean onReceivePushMessage(PushNotificationMessage pushNotificationMessage) {
                    Logger.d("pushNotificationMessage : %s", pushNotificationMessage.getObjectName());
                    return true;
                }
            });
            RongIMClient.setConnectionStatusListener(new RongIMClient.ConnectionStatusListener() {
                @Override
                public void onChanged(ConnectionStatus connectionStatus) {
                    AppConstant.connectionStatus = connectionStatus;
                    Logger.d("AppConstant.connectionStatus : %s", connectionStatus.getMessage());
                    EventBus.getDefault().post(new RongConnectionStatus(connectionStatus));
                }
            });
        }
    }

    private String getCurProcessName() {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager
                .getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    /**
     * 接收消息监听
     */
    RongIMClient.OnReceiveMessageListener onReceiveMessageListener = new RongIMClient.OnReceiveMessageListener() {
        @Override
        public boolean onReceived(Message message, int i) {
            Logger.d("message : %s  , i = %d", message.getObjectName(), i);
            if (AppConstant.ShowTalk &&
                    message.getTargetId().contains(AppConstant.CityCode)) {//判断当前城市是否开启,新消息是否属于当前城市
                //通知显示逻辑
                if (AppConstant.userDo.isPushChat() &&
                        activityCount < 1) {//判断通知开启条件
                    boolean canNotification;//是否可以通知
                    if (SprfUtil.getBoolean(getApplicationContext(), SprfConstant.PUSH_LIMIT, false)) {//是否限制通知时间
                        GregorianCalendar calendar = new GregorianCalendar();
                        calendar.setTimeInMillis(System.currentTimeMillis());
                        int thenDayHour = calendar.get(Calendar.HOUR_OF_DAY);
                        canNotification = thenDayHour < 9 || thenDayHour > 22;
                    } else {
                        canNotification = true;
                    }
                    if (canNotification) {
                        RongNotification rongNotification = new RongNotification(getApplicationContext());
                        rongNotification.notification(message);
                    }
                }
                //页面显示逻辑
                EventBus.getDefault().post(new RongReceiveMessage(message));
            }
            return true;
        }
    };

    /**
     * Activity生命周期全局回调
     */
    ActivityLifecycleCallbacks activityLifecycleCallbacks = new ActivityLifecycleCallbacks() {

        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            if (activity instanceof MainActivity) {
                SprfUtil.setBoolean(activity, SprfConstant.MAIN_ACTIVITY_OPEN, true);
            }
        }

        @Override
        public void onActivityStarted(Activity activity) {
            activityCount++;
        }

        @Override
        public void onActivityResumed(Activity activity) {

        }

        @Override
        public void onActivityPaused(Activity activity) {

        }

        @Override
        public void onActivityStopped(Activity activity) {
            activityCount--;
        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

        }

        @Override
        public void onActivityDestroyed(Activity activity) {
            if (activity instanceof MainActivity) {
                SprfUtil.setBoolean(activity, SprfConstant.MAIN_ACTIVITY_OPEN, false);
            }
        }
    };
}
